package com.mnb.beidou.service;


import com.alibaba.fastjson.JSON;
import com.mnb.beidou.handler.TcpMessageHandler;
import com.mnb.beidou.mapper.CusOrimesMapper;
import com.mnb.beidou.mapper.StPptnRMapper;
import com.mnb.beidou.mapper.StRiverRMapper;
import com.mnb.beidou.mapper.StStbprpBMapper;
import com.mnb.beidou.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TCP消息服务
 */
@Service
public class TcpMessageService {

    private static final Logger logger = LoggerFactory.getLogger(TcpMessageService.class);

    @Autowired
    private List<TcpMessageHandler> messageHandlers;

    private final Map<String, TcpMessageHandler> handlerMap = new ConcurrentHashMap<>();

    @Autowired
    private CusOrimesMapper cusOrimesMapper;

    @Autowired
    private StPptnRMapper stPptnRMapper;

    @Autowired
    private StRiverRMapper stRiverRMapper;

    @Autowired
    private StStbprpBMapper stStbprpBMapper;

    @PostConstruct
    public void init() {
        // 初始化处理器映射
        for (TcpMessageHandler handler : messageHandlers) {
            handlerMap.put(handler.getSupportedMessageType(), handler);
            logger.info("注册消息处理器: {} -> {}", handler.getSupportedMessageType(), handler.getClass().getSimpleName());
        }
    }

    /**
     * 处理TCP消息
     *
     * @param message 接收到的消息
     * @return 响应消息
     */
    public PSDataEntity processMessage(String message, Date time) {
        TcpMessageHandler handler = handlerMap.get("TCP-DATA");
        PSDataEntity entity = new PSDataEntity();
        CusOrimes cusOrimes = new CusOrimes();
        try {
            entity = handler.handleMessage(message);
            if (entity == null) {
                return null;
            }
            cusOrimes.setFromCard(entity.getSrcAddr());
            cusOrimes.setToCard(entity.getDestAddr());
            if(time == null){
                cusOrimes.setTime(new Date());
            }else{
                cusOrimes.setTime(time);
            }
            cusOrimes.setContent(message);
            String msgJson = null;
            if (entity != null && entity.getModbusDataEntity() != null
                    && entity.getModbusDataEntity().getDataEntity() != null
                    && entity.getModbusDataEntity().getDataEntity().getMsgJson() != null) {
                msgJson = entity.getModbusDataEntity().getDataEntity().getMsgJson();
            }
            insertOriMessage(cusOrimes, msgJson);

            String stcd = stStbprpBMapper.selectStcdByIdcard(entity.getSrcAddr());
            if (!StringUtils.isEmpty(stcd)) {
                cusOrimes.setStcd(stcd);
                insertStPptnR(cusOrimes, entity.getModbusDataEntity());
                insertStRiverR(cusOrimes, entity.getModbusDataEntity());
            }
            return entity;
        } catch (Exception e) {
            logger.error("处理消息时发生错误: {}", message, e);
            insertExOriMessage(message, e.getMessage());
        }
        return null;
    }

    public CusOrimes insertOriMessage(CusOrimes cusOrimes, String msgJson) {
        cusOrimes.setReceiveTm(new Date());
        cusOrimes.setStatus(0);
        cusOrimes.setMsgJson(msgJson);
        cusOrimesMapper.insert(cusOrimes);
        return cusOrimes;
    }

    public void insertExOriMessage(String message, String errorMsg) {
        CusOrimes cusOrimes = new CusOrimes();
        cusOrimes.setContent(message);
        cusOrimes.setReceiveTm(new Date());
        cusOrimes.setStatus(1);
        cusOrimesMapper.insert(cusOrimes);
    }

    private void insertStRiverR(CusOrimes cusOrimes, ModbusDataEntity parse) {
        StRiverR stRiverR = new StRiverR();
        stRiverR.setStcd(cusOrimes.getStcd());
        stRiverR.setTm(cusOrimes.getTime());
        stRiverR.setZ(new BigDecimal(parse.getDataEntity().getRadarWaterLevel()));
        stRiverR.setQ(new BigDecimal(parse.getDataEntity().getInstantaneousFlow()));
        stRiverRMapper.insert(stRiverR);
    }

    private void insertStPptnR(CusOrimes cusOrimes, ModbusDataEntity parse) {
        StPptnR stPptnR = new StPptnR();
        stPptnR.setStcd(cusOrimes.getStcd());
        stPptnR.setTm(cusOrimes.getTime());
        stPptnR.setDrp(new BigDecimal(parse.getDataEntity().getCurrentRainfall()));
        stPptnRMapper.insert(stPptnR);
    }
}
